//这个路由负责文件上传
const express = require('express')
const multer = require('multer')
const fs = require('fs')
const path = require('path')
const upload = multer({})
const router = express.Router()

router.post('/img',upload.single('hehe'),(req,res)=>{
  console.log(req.file)
  let {buffer,mimetype,size} =req.file
  if(size >= 60000){
    return res.send({err:-1,msg:'图片尺寸过大'})
  }
  //限制文件类型
  let types = ['jpg','gif','jpeg','png']
  let exName = mimetype.split('/')[1]
  if(types.indexOf(exName)===-1){
    return res.send({err:-2,msg:'图片类型错误'})
  }
  //将文件写到静态资源路径下
  let name = (new Date()).getTime()+`_`+parseInt(Math.random()*99999)
  fs.writeFile(path.join(__dirname,`../public/img/${name}.${exName}`),buffer,(err)=>{
    if(err){
      //http://localhost:3000/public/img/1603429795350_99601.jpeg
      res.send({err:-3,msg:'上传失败'})
    }else{
      res.send({err:0,msg:'上传ok',path:`/public/img/${name}.${exName}`})
    }
  })
})

module.exports = router
